package com.wlb365.financing.modules.schedule.job;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wlb365.financing.modules.schedule.job.domain.UserResult;
import com.wlb365.financing.modules.sys.entity.User;
import com.wlb365.financing.modules.sys.service.IUserService;
import com.wlb365.sdk.client.SdkClient;
import com.wlb365.sdk.model.CommonRequest;
import com.wlb365.sdk.model.CommonResponse;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 概述：定时同步兰格用户信息
 * </p>
 */
@Slf4j
@Component
public class LGUserSyncJob extends QuartzJobBean {
    @Autowired
    private SdkClient sdkClient;

    @Autowired
    private IUserService userService;


    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext){

        //同步兰格机构信息
        CommonRequest request = new CommonRequest("fs.query.org-sync-user");
        //查询参数
        Map<String, Object> param = new HashMap<>();

        request.setBizModel(param);
        CommonResponse response = sdkClient.execute(request);
        if ("000000".equals(response.getCode())) {
            JSONArray jsonArray = JSONUtil.parseArray(response.getData());
            List<UserResult> userResults = jsonArray.toList(UserResult.class);
            userResults.forEach(userResult -> {
                User user = new User();
                BeanUtil.copyProperties(userResult, user);
                UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("com_id", userResult.getCompId());
                userService.saveOrUpdate(user, updateWrapper);
            });


        }


    }
}
